<?php
/**
 * Created by PhpStorm.
 * User: FDG296
 * Date: 2017/7/10
 * Time: 14:56
 */
namespace backend\controllers;

use backend\models\AuthAccess;
use backend\models\AuthRule;
use backend\models\UserRole;
use backend\models\UserRoleGroup;
use Yii;
use yii\web\AdminController;
use common\helps;
use yii\data\Pagination;
use backend\models\Menu;
use common\helps\tools;

class SysRoleController extends AdminController{
    public $layout = false;
    //业务关键字
    public $service = 'SysRole';

    /**
     * 局部关闭csrf
     * action 方法名
     */
    public function beforeAction($action){

        $currentaction = $action->id;

        $novalidactions = ['disable','enable','del-depart','mod-depart','update-role','add-role',
            'disable-group','enable-group','update-role-group','add-role-group','add-rules'];

        if(in_array($currentaction,$novalidactions)) {

            $action->controller->enableCsrfValidation = false;

        }
        parent::beforeAction($action);

        return true;
    }

    /**
     * 首页
     */
    public function actionIndex(){

        //编辑用
        //$list = UserRoleGroup::find()->asArray()->all();

        //新增用
        //$list_group = UserRoleGroup::find()->where(array('use_flg'=>1))->asArray()->all();

        //获取菜单列表，用于权限管理
        $menu_list = Menu::find()->orderBy(array('sort'=>SORT_ASC))->asArray()->all();

        foreach($menu_list as &$value){
            $value['html'] = '';
        }

        $menu_list_tree = \common\helps\tools::getCustomerTree($menu_list,0,0);
        //$this->getMenuTree($menu_list,0,0);
        $this->saveLog($this->service,'角色维护','VIEW', '');
        //return $this->render('index',['list'=>$list,'list_group'=>$list_group,'menu_list'=>$menu_list_tree]);
        return $this->render('index',['menu_list'=>$menu_list_tree]);
    }

    /**
     * 列表
     */
    public function actionGetRoleList(){
        $data = Yii::$app->request->post();

        $condition = array();
        if(!empty($data['role_name'])){
            $condition = ['like', 'r.role_name', $data['role_name']];
        }
        $query = UserRole::find()->where($condition)->alias('r');
        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);
        //$pagination->pageSizeLimit = [$data['start'] > 0 ? $data['start'] : 1 ,$data['length']];

        $list = $query->offset($data['start'])->limit($data['length'])
            ->leftJoin('j_user_role_group as g','r.role_group_id = g.id')
            ->select('r.*,g.role_group_name')
            ->orderBy(array('r.id'=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->asArray()->all();
        if(empty($list)){
            $list = array();
        }

        //相关参数   http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    public function actionGetOneRole(){
        $data = Yii::$app->request->post();

        $result = UserRole::find()->where(array('id'=>$data['id']))->asArray()->one();
        
        $list_group = UserRoleGroup::find()->where(array('use_flg'=>1))->asArray()->all();
        
        $result['list_group'] = $list_group;
        $this->retJson($result, 200);
    }

    public function actionGetRoleGroup(){
        $result = UserRoleGroup::find()->where(array('use_flg'=>1))->asArray()->all();
        $this->retJson($result, 200);
    }
    /**
     * 增加角色
     */
    public function actionAddRole(){
        $model = new UserRole();
        $data = Yii::$app->request->post();


        $data_now['role_name'] = trim($data['role_name']);
        $data_now['create_time'] = date('Y-m-d H:i:s',time());
        $data_now['creator'] = $model->getCreator();
        $data_now['role_group_id'] = $data['role_group_id'];
        $data_now['use_flg'] = $data['use_flg'];

        $res = Yii::$app->db->createCommand()->insert('j_user_role',$data_now)->execute();
        if($res > 0){
            $this->saveLog($this->service,'角色维护','ADD', '新增角色：' .$data_now['role_name'] . "\r\n" . \yii\helpers\Json::encode($data_now));        //日志
            $this->retJson('角色增加成功',200);
        }else{
            $this->retJson('角色增加失败',500);
        }
    }

    /**
     * 修改角色信息
     */
    public function actionUpdateRole(){
        $model = new UserRole();
        $data = Yii::$app->request->post();

        $data_now['role_name'] = $data['role_name'];
        $data_now['role_group_id'] = $data['role_group_id'];
        $data_now['memo'] = $data['memo'];
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $data_now['editor'] = $model->getCreator();

        $res = $model::updateAll($data_now, " id = ".$data['id']);
        if($res > 0){
            $this->saveLog($this->service,'角色维护','MOD', '修改角色：' .$data_now['role_name'] . "\r\n" . \yii\helpers\Json::encode($data_now));
            $this->retJson('角色修改成功',200);
        }else{
            $this->retJson('角色修改失败',500);
        }
    }

    /**
     * 禁用角色
     */
    public function actionDisable(){
        $model = new UserRole();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 0;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, " id = ".$data['id']);

        if($res > 0){
            $this->saveLog($this->service,'角色维护','USEFLG0', '禁用角色 ID =' .$data['id'] . "\r\n" . \yii\helpers\Json::encode($mod_data));
            $this->retJson('禁用成功',200);
        }else{
            $this->retJson('禁用失败',500);
        }
    }

    /**
     * 启用角色
     */
    public function actionEnable(){
        $model = new UserRole();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 1;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, " id = ".$data['id']);

        if($res > 0){
            $this->saveLog($this->service,'角色维护','USEFLG1', '启用角色 ID =' .$data['id'] . "\r\n" . \yii\helpers\Json::encode($mod_data));
            $this->retJson('启用成功',200);
        }else{
            $this->retJson('启用失败',500);
        }
    }

    /**
     * 角色组
     */
    public function actionRoleGroup(){
        $this->saveLog($this->service,'角色组维护','VIEW', '');
        return $this->render('role-group');
    }

    /**
     * 角色组表
     */
    public function actionGetRoleGroupList(){
        $data = Yii::$app->request->post();

        $condition = array();
        if(!empty($data['role_group_name'])){
            $condition = ['like', 'role_group_name', $data['role_group_name']];
        }
        $query = UserRoleGroup::find()->where($condition);
        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count]);
        //$pagination->pageSizeLimit = [$data['start'] > 0 ? $data['start'] : 1 ,$data['length']];

        $list = $query->offset($data['start'])->limit($data['length'])
            ->orderBy(array('id'=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->all();
        if(empty($list)){
            $list = array();
        }

        //相关参数   http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    public function actionGetOneRoleGroup(){
        $data = Yii::$app->request->post();

        $result = UserRoleGroup::findOne(array('id'=>$data['id']));
        return \yii\helpers\Json::encode($result);
    }

    /**
     * 修改角色组信息
     */
    public function actionUpdateRoleGroup(){
        $model = new UserRoleGroup();
        $data = Yii::$app->request->post();

        $data_now['role_group_name'] = $data['role_group_name'];
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $data_now['editor'] = $model->getCreator();
        $data_now['use_flg'] = $data['use_flg'];

        $res = $model::updateAll($data_now, " id = ".$data['id']);
        if($res > 0){
            $this->saveLog($this->service,'角色组维护','MOD', '修改角色组：' .$data_now['role_group_name'] . "\r\n" . \yii\helpers\Json::encode($data_now));
            $this->retJson('角色组修改成功',200);
        }else{
            $this->retJson('角色组修改失败',500);
        }
    }

    /**
     * 增加角色组
     */
    public function actionAddRoleGroup(){
        $model = new UserRoleGroup();
        $data = Yii::$app->request->post();

        $data_now['role_group_name'] = trim($data['role_group_name']);
        $data_now['create_time'] = date('Y-m-d H:i:s',time());
        $data_now['creator'] = $model->getCreator();
        $data_now['use_flg'] = $data['use_flg'];

        $res = Yii::$app->db->createCommand()->insert('j_user_role_group',$data_now)->execute();
        if($res > 0){
            $this->saveLog($this->service,'角色组维护','ADD', '新增角色组：' .$data_now['role_group_name'] . "\r\n" . \yii\helpers\Json::encode($data_now));
            $this->retJson('角色组增加成功',200);
        }else{
            $this->retJson('角色组增加失败',500);
        }
    }

    /**
     * 禁用角色组
     */
    public function actionDisableGroup(){
        $model = new UserRoleGroup();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 0;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, " id = ".$data['id']);

        if($res > 0){
            $this->saveLog($this->service,'角色组维护','USEFLG0', '禁用角色组 ID= ' .$data['id'] . "\r\n" . \yii\helpers\Json::encode($mod_data));
            $this->retJson('禁用成功',200);
        }else{
            $this->retJson('禁用失败',500);
        }
    }

    /**
     * 启用角色组
     */
    public function actionEnableGroup(){
        $model = new UserRoleGroup();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 1;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, " id = ".$data['id']);

        if($res > 0){
            $this->saveLog($this->service,'角色组维护','USEFLG1', '启用角色组 ID= ' .$data['id'] . "\r\n" . \yii\helpers\Json::encode($mod_data));
            $this->retJson('启用成功',200);
        }else{
            $this->retJson('启用失败',500);
        }
    }

    /**
     * 增加角色组
     */
    public function actionAddRules(){
        $data = Yii::$app->request->post();
        $modal = new AuthAccess();
        if(empty($data['rules'])){
            $data['menu_id'] = '';
        }else{
            $data['menu_id'] = implode(',',$data['rules']);
        }
        //通过菜单id找到规则id
        $where = ['in','menu_id',$data['rules']];
        $menu_id_list = AuthRule::find()->where($where)->select('id')->asArray()->all();
        $res = AuthAccess::find()->where(array('role_id'=>$data['role_id']))->asArray()->all();
        $redis = new helps\redisHelper();
        $old_user_info = $redis->getloginUserInfo();
        $user_rule_arr = [];
        if(empty($res)){
            //新增
            $data_row['role_id'] = $data['role_id'];
            $data_row['create_time'] = date('Y-m-d H:i:s',time());
            $data_row['creator'] = $modal->getCreator();

            if(!empty($menu_id_list)){
                $data_row['rule_id'] = implode(',',array_column($menu_id_list,'id'));
                $ret = Yii::$app->db->createCommand()->insert('j_auth_access',$data_row)->execute();
                if($ret > 0){
                    $this->saveLog($this->service,'角色维护','ADD', '角色权限更新 '. "\r\n" . \yii\helpers\Json::encode($data_row));
                }else{
                    $this->retJson('操作失败',500);
                }
            }
        }else{
            //编辑
            $data_row['role_id'] = $data['role_id'];
            $data_row['edit_time'] = date('Y-m-d H:i:s',time());
            $data_row['editor'] = $modal->getCreator();
            $data_row['rule_id'] = implode(',',array_column($menu_id_list,'id'));
            if(!empty($menu_id_list)){
                $data_row['rule_id'] = implode(',',array_column($menu_id_list,'id'));
                $ret = $modal->updateAll($data_row, " role_id = ".$data['role_id']);
                if($ret > 0){
                    $this->saveLog($this->service,'角色维护','MOD', '角色权限更新 '. "\r\n" . \yii\helpers\Json::encode($data_row));
                }else{
                    $this->retJson('操作失败',500);
                }
            }
        }
        $user_rule_arr = tools::getUserRule($old_user_info->userId);
        $redis->setLoginInfo(array(
            'userName'=>$old_user_info->userName,
            'userPwd'=>$old_user_info->userPwd,
            'userId'=>$old_user_info->userId,
            'user_rule'=>$user_rule_arr
        ));
        $this->retJson('操作成功',200);
    }

    //获取角色的权限id
    public function actionGetRule(){
        $data = Yii::$app->request->post();
        $list = AuthAccess::find()->where(array('role_id'=>$data['role_id']))->asArray()->one();
        if(!empty($list)){
            $list_array = explode(',',$list['rule_id']);

            $where = ['in','id',$list_array];
            $res = AuthRule::find()->where($where)->select('menu_id')->asArray()->all();

            if(!empty($res)){
                $result = array_column($res,'menu_id');
            }else{
                $result = null;
            }
        }else{
            $result = null;
        }
        return \yii\helpers\Json::encode($result);
    }
}